<?php

namespace lib\Server;


use lib\Root;

class WebSocketServer extends Server
{
	static public function startServer()
	{
		if (Server::$swoole_instance) {
			Root::stdout("Cannot create WebSocket server from other master processes!");
			Server::$swoole_instance->shutdown();
			exit();
		}

		$_self            = new self();
		$websocket_server = new \swoole_websocket_server("0.0.0.0", 9501);
		$websocket_server->on('open', [$_self, 'open']);
		$websocket_server->on('message', [$_self, 'message']);
		$websocket_server->on('close', [$_self, 'close']);
		$websocket_server->start();

		Server::$swoole_instance = $websocket_server;
	}

	public function open(\swoole_websocket_server $server, $request)
	{
		echo "server: handshake success with fd{$request->fd}\n";
	}

	public function message(\swoole_websocket_server $server, $frame)
	{
		echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
		$server->push($frame->fd, "this is server");
	}

	public function close($ser, $fd)
	{
		echo "client {$fd} closed\n";
	}
}